package com.happyma.bbn.player;

import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import com.google.android.exoplayer2.DefaultRenderersFactory;
import com.google.android.exoplayer2.PlaybackPreparer;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.database.DatabaseProvider;
import com.google.android.exoplayer2.database.ExoDatabaseProvider;
import com.google.android.exoplayer2.source.hls.HlsMediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory;
import com.google.android.exoplayer2.upstream.FileDataSource;
import com.google.android.exoplayer2.upstream.cache.Cache;
import com.google.android.exoplayer2.upstream.cache.CacheDataSource;
import com.google.android.exoplayer2.upstream.cache.CacheDataSourceFactory;
import com.google.android.exoplayer2.upstream.cache.NoOpCacheEvictor;
import com.google.android.exoplayer2.upstream.cache.SimpleCache;
import com.google.android.exoplayer2.util.Util;

import java.io.File;


public class PlayerService extends Service{
    public SimpleExoPlayer player;
    private Intent serviceIntent;
    private int contentType;
    private Uri contentUri;
    private String contentId;
    private String provider;
    private DefaultTrackSelector trackSelector;
    private HlsMediaSource hlsMediaSource;
    private DataSource.Factory dataSourecFactory;

    private static final String DOWNLOAD_CONTENT_DIRECTORY = "downloads";
    private static final String DOWNLOAD_ACTION_FILE = "actions";

    protected String userAgent;
    private File downloadDirectory;
    private Cache downloadCache;
    private DatabaseProvider databaseProvider;

    private static final String TAG = "PlayerService";

    public PlayerService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        userAgent = Util.getUserAgent(this, "BBN");
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return new LocalBinder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        serviceIntent = intent;
        contentType = intent.getIntExtra("content_type", 1);
        contentUri = intent.getData();
        if (player == null) {
            onShown();
        } else {
            releasePlayer();
        }
        return START_STICKY;
    }

    private void onShown() {
        contentUri = serviceIntent.getData();
        contentType = serviceIntent.getIntExtra("content_type", Util.inferContentType(contentUri, serviceIntent.getStringExtra("type")));
        contentId = serviceIntent.getStringExtra("content_id");
        provider = serviceIntent.getStringExtra("provider");
        if (player == null) {
            preparePlayer(true);
        }
    }

    private void preparePlayer(boolean isPlay) {
        if (player == null) {
            dataSourecFactory = buildDataSourceFactory();
            initPlayer();
        }
        player.setPlayWhenReady(isPlay);
    }

    public DataSource.Factory buildDataSourceFactory() {
        return ((DemoApplication)getApplication()).buildDataSourceFactory();
    }

    private void initPlayer() {
        TrackSelection.Factory trackSelectionFactory =
                new AdaptiveTrackSelection.Factory();
        final DefaultTrackSelector.Parameters trackSelectorParameters =
                new DefaultTrackSelector.ParametersBuilder(this).build();
        trackSelector = new DefaultTrackSelector(this, trackSelectionFactory);
        trackSelector.setParameters(trackSelectorParameters);
        SimpleExoPlayer.Builder simpleExoplayerBuilder = new SimpleExoPlayer.Builder(this,
                new DefaultRenderersFactory(this));
        simpleExoplayerBuilder.setTrackSelector(trackSelector);
        player = simpleExoplayerBuilder.build();
//        pv_view.setPlayer(player);
//        Uri uri = Uri.parse("https://bbnchinese-lh.akamaihd.net/i/BibleBroadcasting_Chineseios@87759/master.m3u8");
        hlsMediaSource = new HlsMediaSource.Factory(dataSourecFactory).createMediaSource(contentUri);
        player.prepare(hlsMediaSource);
    }

    public void destroyPlayer() {
        releasePlayer();
    }

      /**
     * 释放资源
     */
    private void releasePlayer() {
        if (player != null) {
            player.release();
            player = null;
            hlsMediaSource = null;
            trackSelector = null;
        }
    }


    public class LocalBinder extends Binder {
        public LocalBinder() {
        }

        public PlayerService getServerInstance() {
            return PlayerService.this;
        }
    }

    public class PlayerActivity  implements PlaybackPreparer{

        @Override
        public void preparePlayback() {
            player.retry();
        }
    }

}